package com.future.mayi.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.future.baselib.utils.CommonUtils;
import com.future.mayi.R;
import com.future.mayi.model.VersionModel;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class UpdateDialog extends Dialog {

    @BindView(R.id.tv_cancel)
    TextView tvCancel;
    @BindView(R.id.tv_upload)
    TextView tvUpload;
    private Activity activity;

    public UpdateDialog(@NonNull Activity activity) {
        super(activity, R.style.dialog);
        this.activity = activity;
        View view = LayoutInflater.from(activity).inflate(R.layout.dialog_update, null);
        view.setMinimumWidth((int) (((float) CommonUtils.getScreenSize(getContext())[0]) * 0.7f));
        setContentView(view);
        ButterKnife.bind(this);
        setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (model == null || TextUtils.isEmpty(model.getDownload())) return false;
                if (model.getIs_force() == 1) {
                    UpdateDialog.this.activity.finish();
                    System.exit(0);
                    return true;
                }
                return false;
            }
        });
    }


    private VersionModel model;

    public void show(VersionModel model) {
        if (model == null) return;
        super.show();
        this.model = model;
        setCancelable(!(model.getIs_force() == 1));
        tvCancel.setVisibility(model.getIs_force() == 1 ? View.GONE : View.VISIBLE);
    }


    @OnClick({R.id.tv_cancel, R.id.tv_upload})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_cancel: {
                dismiss();
            }
            break;
            case R.id.tv_upload: {
                if (model == null || TextUtils.isEmpty(model.getDownload())) return;
                if (!(model.getIs_force() == 1)) {
                    dismiss();
                }
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(model.getDownload());
                intent.setData(content_url);
                activity.startActivity(intent);
            }
            break;
        }
    }
}
